<?php
/**
 * Контроллер магазинов
 * 
 * Управление тегами
 * @author Anton Zavidov
 * @package myLiveShop
 */

/**
 * Класс контроллера для управления магазинов
 *
 */
class ControllerShop extends Element{
    
    private $shop;
    private $shop_info;
	/**
	 * Констуктор
	 *
	 * @param string $className имя контроллера
	 */
	public function __construct($className=null){
		$this->name='shop';
		parent::__construct($className?$className:__CLASS__);
	}
	/**
	 * Просмотр елемента
	 *
	 */
	public function show($page=1){
		parent::show();
		$this->view->set(
			'list',
			$this->model()->load(
				false,
				array(
					ModelShop::F_SHOP_ID,
					ModelShop::F_TITLE,
					ModelShop::F_NAME
				),
				$page===false?null:array(
					'pagination'=>array(
						'page'=>$page,
						'show'=>true
					)
				)
			)
		);
		$this->view->set('pagination',$this->model()->pagination);
        $this->build();
	}
	/**
	 * Просмотр елемента
	 *
	 */
	public function showByUser(){
		$this->shop = Requestlocal::getString('name', false);
		$this->display();
	}
	/**
	 * Просмотр елемента
	 *
	 */
	public function display(){
		parent::display(false);
		$view='info';
		if(!$this->shop){
			$this->shop=Vars::_(Router::SHOP);
			$view='display';
		}
		$this->shop_info=$this->model()->loadOne(null,false,array('where'=>ModelShop::F_NAME.'="'.$this->shop.'"'));
		///надо чем то заменить
		$this->shop_info['category_name'] = $this->shop_info['category_id'] ? $this->model('category')->loadOne($this->shop_info['category_id'],array(ModelCategory::F_TITLE)) : '';
		$this->shop_info['currency_name'] = $this->shop_info['currency_id'] ? $this->model('currency')->loadOne($this->shop_info['currency_id'],array(ModelCurrency::F_NAME)) : '';
		$this->shop_info['template_name'] = $this->shop_info['template_id'] ? $this->model('template')->loadOne($this->shop_info['template_id'],array(ModelTemplate::F_TITLE)) : '';
		$this->shop_info['categories'] = $this->model('category')->loadCount(array('where'=>ModelCategory::F_SHOP_ID .'='.$this->shop_info['shop_id']));
		$this->shop_info['articles'] = $this->model('article')->loadCount(array('where'=>ModelArticle::F_SHOP_ID .'='.$this->shop_info['shop_id']));
		$this->shop_info['products'] = $this->model('product')->loadCount(array('where'=>ModelProduct::F_SHOP_ID .'='.$this->shop_info['shop_id']));
		$this->shop_info['orders'] = $this->model('order')->loadCount(array('where'=>ModelOrder::F_SHOP_ID .'='.$this->shop_info['shop_id']));
		$this->shop_info['tags'] = $this->model()->getAllTags($this->shop_info['shop_id']);
		$this->shop_info['image'] = import('helper.image',true)->get($this->shop_info['image_id']);
		$this->view->set('info',$this->shop_info);
		$this->build($view);
		
	}
	/**
	 * Получение информации об элементах магазина
	 *
	 */
	public function getShopInfo(){
		$this->view->set('categories',$this->model('category')->load(null,false,array('where'=>ModelCategory::F_SHOP_ID .'='.$this->shop_info['shop_id'])));
		$this->view->set('articles',$this->model('article')->load(null,false,array('where'=>ModelArticle::F_SHOP_ID .'='.$this->shop_info['shop_id'])));
		$this->view->set('products',$this->model('product')->load(null,false,array('where'=>ModelProduct::F_SHOP_ID .'='.$this->shop_info['shop_id'])));
	}
    /**
	 * Проверка имени магазина
	 *
	 */
	public function checkShopName($name=false){
        $errors = array();
		$checkName =  $name ? $name : Requestlocal::getString('name', false);
        if(!$checkName || !preg_match("/[a-z0-9_]/i",$checkName)){
            $errors[ModelShop::F_NAME] = T::_('Invalid name');
        }
        if(!$errors){
            if($this->model()->getId($checkName))  $errors[ModelShop::F_NAME] = T::_('Name exist');
        }
        if(count($errors) && Core::isJSON()) {
            $this->view->result($errors);
            return;
        } elseif(count($errors)) return false;
        else return true;

	}
	/**
	 * Форма редактирования
	 *
	 */
	public function edit(){
		Core::mustLogin();
		L($this->name.' Edit');
		$this->findId(true);
		$this->show_view=__FUNCTION__;
		if($this->id ){
		    if(is_string($this->id)){
		          $this->shop=$this->cleanName($this->id);
		          $this->view->set('element',$this->model()->loadOne(false,false,array('where'=>ModelShop::F_NAME.'="'.$this->shop.'"')));
		    }else{
		          $this->view->set('element',$this->model()->loadOne($this->id));
		    }
		}
		$this->build();
	}
	/**
	 * Форма создания
	 *
	 */
	public function add(){
		parent::add();
		Core::mustLogin();
		$this->build();
	}
    /**
    * Регистрация
    *
    */
    public function register(){
        $errors = array();
        if(!$this->checkShopName(Requestlocal::getString('namer'))){
            $errors[ModelShop::F_NAME] = T::_('Name exist');
        }
        if(count($errors) && Core::isJSON()) {
            $this->view->result($errors);
            return;
        }elseif(count($errors)){
            Core::setFormErrors($result);
			Core::saveReferer();
			Core::saveRequest();
			Core::redirect(Core::getReferer(true),T::_('Error'));
            return;
        }
        $this->save();
    }
	/**
	 * Создание
	 *
	 */
	public function save(){
		parent::save();
		if(!Core::mustLogin()) return false;
		$shop_id = Requestlocal::getInt(ModelShop::F_SHOP_ID,null,'post');
		$image_id = Requestlocal::getInt(ModelShop::F_IMAGE_ID, 0);
		if($shop_id && !$image_id) $image_id = '0';
		$save_data = array(
			ModelShop::F_CATEGORY_ID=>Requestlocal::getInt(ModelShop::F_CATEGORY_ID),
			ModelShop::F_CURRENCY_ID=>Requestlocal::getInt(ModelShop::F_CURRENCY_ID, 1),
			ModelShop::F_TEMPLATE_ID=>1,
			ModelShop::F_IMAGE_ID=>$image_id,
			ModelShop::F_TITLE=>Requestlocal::getString(ModelShop::F_TITLE),
			ModelShop::F_DESCRIPTION=>Requestlocal::getString(ModelShop::F_DESCRIPTION),
			ModelShop::F_USER_ID=>Core::user(),
			ModelShop::F_LANG_ID=>Core::lang(),
			ModelShop::F_CREATED=>Core::date(),
			ModelShop::F_PUBLISH=>"F",//Core::setAccess(),
			ModelShop::F_TEMPLATE_SETTINGS=>"{}"
		);
		if(!$shop_id){
			$save_data[ModelShop::F_NAME] = Requestlocal::getString(ModelShop::F_NAME);
		}
		$result=$this->model()->save($save_data,$shop_id);
		if(is_numeric($result)){
            $shop_id = $result;
        }
        if(is_array($result)){
        	$this->view->result($result);
        } else {
        	if($shop_id) {
	            //устанавливаем метки
	            import('helper.tag');
	            HelperTag::setTags('shop', $shop_id, Requestlocal::getString('tag_id','[]','post'));
	        }
        	if($image_id && $image_id!='0' && Requestlocal::getInt('newImage',0)){
            	import('helper.image',true)->setModule($image_id,'shop',$shop_id);
            } elseif (Requestlocal::getInt('newImage',0)){
            	import('helper.image',true)->deleteImageFromModule('shop',$shop_id);
            }
        	$this->view->result(false);
        }
	}
	/**
	 * Удаление
	 *
	 */
	public function delete(){
		if(!Core::mustLogin()) return false;
		L($this->name.' Delete');
		$this->findId(true);
		if($this->id ){
		    $this->shop=$this->cleanName($this->id);
		    import('helper.image',true)->deleteImageFromModule($this->id, $this->name);
		    $this->model()->delete(false,array('where'=>ModelShop::F_NAME.'="'.$this->shop.'"'));
		}
		Core::redirect(base64_decode(Vars::_(Core::REFERER)),T::_('Deleted'));
	}
	
	public function __call($shop_name,$params){
	    $this->shop=$this->cleanName($shop_name);
	    $this->display();
	}
	
	private function cleanName($name){
		return  Filterinput::getInstance()->clean($name);
	}
}